﻿using System;
using System.Collections.Generic;
using System.Linq;
using Viettel.VOFFICE.DAO.DAL.Paging;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    public class OfficePartnerRepository : IRepository<OfficePartner>
    {
        private VOFFICEContext context;

        public OfficePartnerRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Connection not found :: ");
            }
            this.context = context;
        }

        public IEnumerable<OfficePartner> Search(string key)
        {
            return context.OfficePartners.Where(o => o.Name.Contains(key));
        }

        public IEnumerable<OfficePartner> Get()
        {
            return context.OfficePartners.Select(o => o);
        }

        public OfficePartner GetById(object id)
        {
            return context.OfficePartners.Find(int.Parse(id.ToString()));
        }

        public IEnumerable<OfficePartner> FindByName(object s)
        {
            throw new NotImplementedException();
        }

        public void Insert(OfficePartner T)
        {
            if (T != null)
            {
                context.OfficePartners.Add(T);
                Save();
            }
        }

        public void Delete(object id)
        {
            var item = GetById(id);
            if (item != null)
            {
                context.OfficePartners.Remove(item);
                Save();
            }
        }

        public void Delete(OfficePartner T)
        {
            throw new NotImplementedException();
        }

        public void Update(OfficePartner T)
        {
            if (T != null)
            {
                context.Entry(T).State = System.Data.EntityState.Modified;
                Save();
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public PagedList<OfficePartner> Paging(int pageIndex, int pageSize)
        {
            return context.OfficePartners.OrderByDescending(o => o.CreatedAt).Paginate(pageIndex, pageSize);
        }

        /// <summary>
        /// Lấy tất cả các phòng ban đối tác văn bản
        /// </summary>
        /// <param name="isActive"></param>
        /// <returns></returns>
        public IEnumerable<OfficePartner> GetByActive(bool isActive = true)
        {
            if (isActive == true)
            {
                return context.OfficePartners.Where(o => o.IsActive == isActive).OrderBy(o => o.Id);
            }
            else
            {
                return context.OfficePartners.Where(o => o.IsActive == false || o.IsActive == null).OrderBy(o => o.Id);
            }
        }
    }
}
